import { StoreType } from "./enum";

/**获取数据 */
function getStore(key) {
  return new Promise((resolve) => {
    if (chrome.storage) {
      chrome.storage.local.get(key, (result) => {
        if (result.hasOwnProperty(key))
          resolve({ ok: true, data: result[key] });
        else resolve({ ok: false });
      });
    } else resolve({ ok: false });
  });
}

/**保存数据 */
function setStore(k, v) {
  chrome.storage && chrome.storage.local.set({ [k]: v });
}

/**获取所有 */
export function getStoreAll() {
  return new Promise((resolve) => {
    if (chrome.storage) {
      const { LANG, SWITCH, ROUTES, TAGS, MODE, REDIRECT } = StoreType;
      chrome.storage.local.get(
        [LANG, SWITCH, ROUTES, TAGS, MODE, REDIRECT],
        (result) => {
          resolve({ ok: true, data: result });
        }
      );
    } else resolve({ ok: false });
  });
}

/**同步全局开关 */
export function setGlobalSwitchOn(value) {
  setStore(StoreType.SWITCH, value);
}

/**获取全局开关状态 */
export async function getGlobalSwitchOn() {
  const { ok, data } = await getStore(StoreType.SWITCH);
  if (ok) return data;
  return true;
}

/**同步请求协议对象 */
export function setProtocol(target) {
  setStore(StoreType.PROTOCOL, target);
}

/**获取请求协议对象 */
export async function getProtocol() {
  const { ok, data } = await getStore(StoreType.PROTOCOL);
  if (ok) return data;
  const initData = {
    get: true,
    post: true,
    put: true,
    delete: true,
  };
  setProtocol(initData);
  return initData;
}

/**同步请求类型对象 */
export function setAjaxType(target) {
  setStore(StoreType.AJAX_TYPE, target);
}

/**获取请求类型对象 */
export async function getAjaxType() {
  const { ok, data } = await getStore(StoreType.AJAX_TYPE);
  if (ok) return data;
  const initData = { xhr: true, fetch: true };
  setAjaxType(initData);
  return initData;
}
